package czh.cocoa.ui;

import czh.cocoa.foundation.NSObject;
import czh.cocoa.foundation.NSString;
import czh.cocoa.graphics.CGRect;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class UIApplication extends UIResponder {
	
	public final static NSString UIApplicationDidReceiveMemoryWarningNotification = 
		                         NSTR("UIApplicationDidReceiveMemoryWarningNotification");

	private static UIApplication sApplication;
	
	private UIApplicationDelegate mDelegate;
	
	private CocoaView mRootView; 
	
	private UIWindow mKeyWindow;
	
	private boolean mStatusBarHidden;
	
	public static UIApplication sharedApplication() {
		if (sApplication == null) {
			sApplication = new UIApplication();
		}
		return sApplication;
	}
	
	private UIApplication() {
		
	}
	
	public void setDelegate(UIApplicationDelegate delegate) {
		mDelegate = delegate;
	}
	
	public UIApplicationDelegate delegate() {
		return mDelegate;
	}
	
	public UIWindow keyWindow() {
		return mKeyWindow;
	}
	
	public void setStatusBarHidden(boolean hidden) { 
		mStatusBarHidden = hidden;
		
		Activity activity = (Activity) mRootView.getContext();
		Window window = activity.getWindow();
		int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
		window.setFlags(hidden ? flag : ~flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}
	
	public boolean isStatusBarHidden() {
		return mStatusBarHidden;
	}
	
	public CGRect statusBarFrame() {
		DisplayMetrics display = getContext().getResources().getDisplayMetrics();
		int status_bar_height = Math.round(25* display.density); 
		return CGRectMake(0, 0, display.widthPixels, status_bar_height);
	}
	
	public View getRootView() {
		return mRootView;
	}
	
	public Context getContext() {
		return mRootView.getContext();
	}
	
//private use --->	
	
	void setRootView(CocoaView view) {
		mRootView = view;
	}
	
	void finishLaunchingWithOptions() {   
		if(mDelegate != null) {
			mDelegate.applicationDidFinishLaunchingWithOptions(this, null);
		}
	}

    void willTerminate() {
    	if(mDelegate != null) {
			mDelegate.applicationWillTerminate(this); 
		}
	}

	void willEnterForeground() {
		if(mDelegate != null) {
			mDelegate.applicationWillEnterForeground(this); 
		}
		mRootView.resumeSoftInputIfNeed();
	}

	void didEnterBackground() {
		if(mDelegate != null) {
			mDelegate.applicationDidEnterBackground(this);
		}
	}
	
	void receiveMenuCommand(int cmd, String title) {
		if(mDelegate != null) {
			mDelegate.applicationDidReceiveMenuCommand(cmd, title);
		}
	}
	
	void setKeyWindow(UIWindow window) {
		if (mKeyWindow != null) {
			mKeyWindow.resignKeyWindow();
		}
		mKeyWindow = window;
		mRootView.setMainLayer(window.layer());
		mRootView.invalidate();
	}
	
}
